// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境
const db = cloud.database()
const axios = require('axios');


// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  console.log(event);
  const code = event.code.code;
  const appid = 'wx8a5b19e4aa3b5500';
  const secret = '084945bbf37afc298695ac2001b56275';
  const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`;
  try {
    let aut = event.user.aut
    let text = aut + '想使用' + event.shuju.name + "。请求允许！！！"
    const res = await axios.get(url);
    const openid = res.data.openid;
    const session_key = res.data.session_key;
    console.log("openid:", openid);
    console.log("session_key:", session_key);
    //获取提醒的openid
    let cp = await db.collection('users').doc(event.user.cpid).get()
    console.log(cp);
    const result = await cloud.openapi.subscribeMessage.send({
      "touser": cp.data.openid,
      "page": 'pages/shangdian/xiaoxi/index',
      "lang": 'zh_CN',
      "data": {
        "thing2": {
          "value": aut
        },
        "thing1": {
          "value": text
        },
        "time3": {
          "value": text
        },
      },
      "templateId": 'VW3Rknu5JUoik5Rnt50i1fx3Og2M13W0y7q_foGSgU8',
      "miniprogramState": 'trial'
    })

    let user = event.user
    let sj = {
      checked: event.shuju.checked,
      df: event.shuju.df,
      id: event.shuju.id,
      kucun: event.shuju.kucun,
      name: event.shuju.name,
      num: event.shuju.num,
      price: event.shuju.price,
      text: event.shuju.text,
      gouwucheid: event.shuju._id,
    }
    //当前时间获取
    let str1 = "使用时间" + date
    //设置数据库的数据
    db.collection(user.gouwuche).doc(event.shuju._id).update({
      data: {
        checked: false,
        id: str1
      }
    })
    //往对方数据库添加数据
    db.collection(user.cpdb).add({
      data: sj
    })
    return {
      faalse: true
    }

  } catch (err) {
    return{faals:false}
  }
}

//格式化时间
function formatDate(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  return [year, month, day].map(formatNumber).join('/')
}
// 辅助函数：格式化数字，确保数字为两位数
function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}